package griffin.website;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import griffin.logic.UserLogic;

public class TopHome extends Activity {

	private static final String TAG = "[TopHome]";
	private static final String SOAP_ACTION = "http://tempuri.org/getBookmarks";
    private static final String METHOD_NAME = "getBookmarks";
    private static final String NAMESPACE = "http://tempuri.org/";
//    private static final String URL = "http://griffin.ciandt.cn/Sservice1.asmx";
    private static final String URL = "http://192.168.3.130:8080/Sservice1.asmx";
	private static final int BOOKMARKNUMS = 4;
	UserLogic userLogic = new UserLogic(this);
	private String loginUserName = "";
	private int loginUserID = 0;
	private List<Map<String, Object>> bookmarkList = new ArrayList<Map<String, Object>>();
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Log.d(TAG, "[onCreate...] ");
    	
        super.onCreate(savedInstanceState);		
        setTitle("Home");
        setContentView(R.layout.tophome);
        
        setNotifyBookmarkUpdatedFlag();
//        Init();                                                                                     
    }
	
	@Override
	public void onResume() {
		super.onResume();	
		Log.d(TAG, "[onResume...] ");	        
		Init();
	}
    
	private void setNotifyBookmarkUpdatedFlag()
	{
		SharedPreferences bookmarkupdateInfo = getSharedPreferences("griffin.website.bookmarkupdatedflag", 0);
    	SharedPreferences.Editor editor = bookmarkupdateInfo.edit();
    	if(bookmarkupdateInfo.contains("bookmarkupdatedflagathome"))
    		editor.remove("bookmarkupdatedflagathome");
    	if(bookmarkupdateInfo.contains("bookmarkupdatedflagatbookmark"))
    		editor.remove("bookmarkupdatedflagatbookmark");
    	//notify home activity to update bookmark list
    	editor.putBoolean("bookmarkupdatedflagathome", true);
    	//notify bookmark activity to update bookmark list
    	editor.putBoolean("bookmarkupdatedflagatbookmark", true);
    	editor.commit();
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
					Log.d(TAG,"[onConfigurationChanged:====LANDSCAPE");
					coverflowNew();	
				}
	}
    
    private void Init(){
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//			Log.d(TAG,"[onConfigurationChanged:====LANDSCAPE");
//			
//			//logic
//			coverflowNew();	
		}else{
			Log.d(TAG,"[onConfigurationChanged:====PORTRAIT");	
			//add 
			ImageView imgPage01=(ImageView)this.findViewById(R.id.btnpage01);
			imgPage01.setOnClickListener(new OnClickListener(){
		 		public void onClick(View v){
					goBack(v);
		 		}
		 	});
//			imgPage01.setOnTouchListener(new TouchItemClickListener());
			imgPage01.setLongClickable(true);
			imgPage01.setTag( "1,Living");
			
			ImageView imgPage02=(ImageView)this.findViewById(R.id.btnpage02);
			imgPage02.setOnClickListener(new OnClickListener(){
	 		public void onClick(View v){
				goBack(v);
	 			}
			});
//			imgPage02.setOnTouchListener(new TouchItemClickListener());
			imgPage02.setLongClickable(true);
			imgPage02.setTag( "2,Leisure");
			
			ImageView imgPage03=(ImageView)this.findViewById(R.id.btnpage03);
			imgPage03.setOnClickListener(new OnClickListener(){
		 		public void onClick(View v){
					goBack(v);
		 		}
		 	});
//			imgPage03.setOnTouchListener(new TouchItemClickListener());
			imgPage03.setLongClickable(true);
			imgPage03.setTag( "3,Tools");
			
			ImageView imgPage04=(ImageView)this.findViewById(R.id.btnpage04);
			imgPage04.setOnClickListener(new OnClickListener(){
		 		public void onClick(View v){
					goBack(v);
		 		}
		 	});
//			imgPage04.setOnTouchListener(new TouchItemClickListener());
			imgPage04.setLongClickable(true);
			imgPage04.setTag( "4,Region");
	        
			getLoginInfo();
	        
			getBookmarkList();	        
	        
			setWelcomeInfo();
		}
    }
    

    
    private void coverflowNew(){	
    	Intent intent =new Intent();
    	intent.putExtra("winname", "CoverFlow"); 
    	intent.setClass(TopHome.this, CoverFlow.class);
    	startActivity(intent);
    }
	
	private void saveCurCategory(String curCategoryID, String curCategoryName) {
		SharedPreferences loginInfo=getSharedPreferences("griffin.website.curcate", 0);
    	SharedPreferences.Editor editor=loginInfo.edit();
    	if(loginInfo.contains("curcategoryid"))editor.remove("curcategoryid");
    	if(loginInfo.contains("curcategoryname"))editor.remove("curcategoryname");
    	editor.putString("curcategoryid", curCategoryID); 	
    	editor.putString("curcategoryname", curCategoryName); 	
    	editor.commit();
	}

 	public void goBack(View imgPage)
 	{
 		String strCategorys=imgPage.getTag().toString();
		String[] strCategory=strCategorys.split(",");
		saveCurCategory(strCategory[0], strCategory[1]);
		Log.d("ME", strCategory[0]+"="+strCategory[1]);
		Intent intent = new Intent();
		intent.putExtra("winname", "CategoryList"); 
		intent.setClass(TopHome.this, TabBarFramework.class);
		startActivity(intent);
 	}
 	
	class TouchItemClickListener implements OnTouchListener
    {
		public boolean onTouch(View v, MotionEvent event) {
			
			Animation homeCategoryAnimation = AnimationUtils.loadAnimation(v.getContext(), R.anim.home_cate_move);
			v.startAnimation(homeCategoryAnimation);
			ImageView imgPage=(ImageView)v;
			if(event.getPointerCount()>=1&&imgPage.getTag()!=null)
			{
				String strCategorys=imgPage.getTag().toString();
				String[] strCategory=strCategorys.split(",");
				saveCurCategory(strCategory[0], strCategory[1]);
				Log.d("ME", strCategory[0]+"="+strCategory[1]);
				Intent intent = new Intent();
				intent.putExtra("winname", "CategoryList"); 
				intent.setClass(TopHome.this, TabBarFramework.class);
				startActivity(intent);
			}
			return true;
		}		
    }
	
	private void getLoginInfo() 
	{
		ImageView btnLoginOut = (ImageView)findViewById(R.id.btnlogout);
		AtomicReference<String> strUsername=new AtomicReference<String>("");
    	AtomicReference<String> strPassword=new AtomicReference<String>("");
    	AtomicInteger userid=new AtomicInteger(0);
		if(userLogic.getLoginUser(strUsername, strPassword, userid)){
			//show loginOut
			btnLoginOut.setVisibility(View.VISIBLE);
			loginUserName = strUsername.get();
			loginUserID = userid.get();
			
			Log.d(TAG, "[Login with] " + loginUserName);		
		}else{
			//hide loginOut
			btnLoginOut.setVisibility(View.INVISIBLE);
			
			Log.d(TAG, "[No Login] ");	
		}
		
		btnLoginOut.setOnClickListener(new OnClickListener(){
	 		public void onClick(View v){
	 			loginOut();
	 		}
	 	});
	}
	
	private void loginOut()
	{
		userLogic.loginOut();
    	
		ImageView btnLoginOut = (ImageView)findViewById(R.id.btnlogout);
    	btnLoginOut.setVisibility(View.INVISIBLE);
	
		Intent intent = new Intent();
		intent.putExtra("winname", "TopHome"); 
		intent.setClass(TopHome.this, TabBarFramework.class);
		startActivity(intent);

	}
	
	private void setWelcomeInfo()
    {
    	TextView tv = (TextView)findViewById(R.id.txtWelcome);
    	if (loginUserName != "")
    	{
    		tv.setText("Hello " + loginUserName + "!");
    	}
    	else
    	{
    		tv.setText("Hello guest,Please login!");
    	}
    }
	
	private void getBookmarkList() 
	{
		if(isLogined()){
			if (isBookmarkUpdated()) {
				bookmarkList.clear();
				ListView topBookmarkedSite = (ListView)this.findViewById(R.id.topBookmarkedSite);
				topBookmarkedSite.setAdapter(new BookMarkListAdapter());
			}
		}
	}
	
	private boolean isLogined()
	{
		if (loginUserID == 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	private boolean isBookmarkUpdated()
	{
		boolean isUpdated = false;
		
		SharedPreferences bookmarkUpdateInfo = getSharedPreferences("griffin.website.bookmarkupdatedflag", 0);
		isUpdated = bookmarkUpdateInfo.getBoolean("bookmarkupdatedflagathome", false);
		//reset current activity update flag to false, so current activity will not update again when bookmark not updated.
		setBookmarkUpdatedFlag(false);
		
		return isUpdated;
	}
	
	private void setBookmarkUpdatedFlag(boolean flag)
	{
		SharedPreferences bookmarkupdateInfo = getSharedPreferences("griffin.website.bookmarkupdatedflag", 0);
    	SharedPreferences.Editor editor = bookmarkupdateInfo.edit();
    	if(bookmarkupdateInfo.contains("bookmarkupdatedflagathome"))
    		editor.remove("bookmarkupdatedflagathome");
    	editor.putBoolean("bookmarkupdatedflagathome", flag);
    	editor.commit();
	}
	
    class BookMarkListAdapter extends SimpleAdapter
    {
		public BookMarkListAdapter()
		{
			super(TopHome.this,getBookmarkData(loginUserID),R.layout.homebookmarklist,
					new String[]{"Bookmarkname"},
					new int[]{R.id.homebookmarktitle});
		}
    	
    	public View getView(int position,View convertView,ViewGroup parent)
    	{
    		HashMap<String, Object> item = (HashMap<String, Object>) bookmarkList.get(position);    
    		
    		LayoutInflater inflater = getLayoutInflater();
    		View row=inflater.inflate(R.layout.homebookmarklist, parent, false);
    		TextView label = (TextView)row.findViewById(R.id.homebookmarktitle);
    		
    		label.setText((String)item.get("Bookmarkname"));
    		label.setTag((String)item.get("Bookmarkurl"));
    		label.setOnClickListener(new BookmarkClickListener());
    		
    		Log.d(TAG, "[getView ].position("+position+")");
    		
    		return row;
    		
    	}
    	
    }
    
	private List<Map<String, Object>> getBookmarkData(int userid)
	{
		if (isLogined())
		{
			try{
				SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		        request.addProperty("userid", userid);
	
		        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		        envelope.dotNet=true;
		        envelope.setOutputSoapObject(request);
	
		        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
		        androidHttpTransport.call(SOAP_ACTION, envelope);
	
		        Object result = (Object)envelope.getResponse();  
		        try 
		        {   
		        	JSONObject jsonObj = new JSONObject(result.toString());
		            JSONArray bookmarkArr = jsonObj.getJSONArray("bookmarks");
		            
		            for(int i = 0; i < bookmarkArr.length() && i < BOOKMARKNUMS; i++)
		            {
		            	Map<String, Object> map = new HashMap<String, Object>();
		            	map.put("Bookmarkurl", bookmarkArr.getJSONObject(i).getString("Bookmarkurl"));
		            	map.put("Bookmarkname", bookmarkArr.getJSONObject(i).getString("Bookmarkname"));
		            	bookmarkList.add(map);
		            }
		        } 
		        catch (JSONException e) 
		        {   
		        	e.printStackTrace();   
		        }    
			}catch(Exception ex){
				ex.printStackTrace(); 
			}
		}
		
		return bookmarkList;
	}
    
    class BookmarkClickListener implements View.OnClickListener
    {
    	public void onClick(View v)
    	{
    		TextView clickbookmark = (TextView)v;
    		String bookmarkurl = clickbookmark.getTag().toString().trim();
    		openUrl(bookmarkurl);
    	}
    }
	
	private void openUrl(String url) 
	{
		Uri uri = Uri.parse(url);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent); 
	}	
	
	@Override
	public void onDestroy() 
	{
		super.onDestroy();
		
//		userLogic.loginOutWhenExit();
		Log.d(TAG,"[onDestroy...]" );
	}
	
//	 @Override
//	    public boolean onKeyDown(int keyCode, KeyEvent event) {
//			Intent intent=getIntent(); 
//		    String value=intent.getStringExtra("winname"); 
//		    Log.d(TAG,"[onKeyDown...<<"+value+">>]" );
////		    if(value!="TopHome"){
////		    	return false;
////		    }
////	        switch (keyCode) {
//////	        case KeyEvent.KEYCODE_3:
//////	            mapController.zoomIn();
//////	            break;
//////	        case KeyEvent.KEYCODE_1:
//////	            mapController.zoomOut();
//////	            break;
////	        }
//	        return super.onKeyDown(keyCode, event);
//     }

	
//	@Override
//	 public boolean onKeyDown(int keyCode, KeyEvent event) {
//		Intent intent=getIntent(); 
//	    String value=intent.getStringExtra("winname"); 
//	    if(value!="TopHome"){
//	    	return false;
//	    }
        
//		  if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//			   final AlertDialog isExit = new AlertDialog.Builder(this).create();
//			   isExit.setTitle("Message");
//			   isExit.setMessage("Are you sure to Exit?");
//			   
//			   DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
//				    public void onClick(DialogInterface dialog, int which) {
//					     switch (which) {
//						     case AlertDialog.BUTTON1:
//						      userLogic.loginOutWhenExit();	 
//						      Log.d(TAG,"[onFinish...]" );
//						      finish();
//						      if(!isFinishing()){
////							      ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
////							      am.restartPackage(getPackageName());
//						      }
//						      break;
//						     case AlertDialog.BUTTON2:
//						    	 isExit.cancel();
//						      break;
//						     default:
//						      break;
//					     }
//				    }
//			   };
//			   isExit.setButton("YES", listener);
//			   isExit.setButton2("Cancel", listener);
//			   isExit.show();
//			   return false;
//		  }
//		 return false;
//	 }
//	private void askloginTip() {
//		AlertDialog.Builder builder= new AlertDialog.Builder(Bookmark.this);
//		builder.setTitle("You are not sign in.Login now?").setPositiveButton("Yes!",new DialogInterface.OnClickListener() {
//			
//			public void onClick(DialogInterface arg0, int arg1) {
//				openIntenInView("Login",Bookmark.this);
//			}
//		});
//		builder.setCancelable(false).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
//			public void onClick(DialogInterface dialog, int id) { 
//				dialog.cancel(); 									
//			} 
//		});
//		builder.create();
//		builder.show();
//	}	
}